# 我在精神病院学斩神
import asyncio
import re

from curl_cffi.requests.session import Session
from pyquery import PyQuery

from app.eBooks.mongo_cols import ZHANSHEN_COL
from utils import chrome_version

# https://fanqienovel.com/page/7143038691944959011
session = Session(impersonate=chrome_version.CHROME124)


async def download_book(chapter_index):
    item: dict = await ZHANSHEN_COL.find_one({"chapter_index": int(chapter_index)})
    if not item:
        return None
    item.pop("_id", None)
    item["next_index"] = item['chapter_index'] + 1
    item["prev_index"] = item['chapter_index'] - 1

    return item
    # return None


async def list_page():
    resp = session.get("http://www.qqwmx.com/info/16022/")
    doc = PyQuery(resp.text)
    chapter_index = 0
    for index, item in enumerate(doc('.listmain dd a').items()):
        if index > 4:
            urlpath = item.attr('href')
            title_id = urlpath.split(".")[0].split("/")[-1],

            r = re.search("第(\d+)章(.*?)$", item.text())
            if r:
                chapter_index = int(r.group(1))
                title = r.group(2)
            else:
                chapter_index += 1
                title = item.text()
            data = {
                "chapter_index": chapter_index,
                "title": title.strip(),
                "title_id": title_id,
                "current_url": f"http://www.qqwmx.com{urlpath}",
                "content": "",
                "content_html": ""
            }
            await ZHANSHEN_COL.update_one(
                {"title_id": title_id, "chapter_index": chapter_index},
                {"$set": data},
                upsert=True
            )


async def download_chapter():
    item = await ZHANSHEN_COL.find_one({"content": ""})
    if item:
        print(item['title'])
        resp = session.get(item['current_url'])
        doc = PyQuery(resp.text)
        await ZHANSHEN_COL.update_one(
            {"_id": item['_id']},
            {
                "$set": {
                    "content": doc("#content").text(),
                    "content_html": doc("#content").html(),
                }
            }
        )


if __name__ == '__main__':
    from db.redis_client import sync_cli


    async def run():
        """"""
        sync_cli.delete('zhanshen_url')
        # chapter_index = sync_cli.get('zhanshen_url')
        # if not chapter_index:
        #     chapter_index = 1
        # while 1:
        #     data = await download_book(chapter_index)
        #     print(f"第{data['chapter_index']}章 {data['title']}")
        #     print(data['content'].replace("\n\n",""))
        #     chapter_index = data['next_index']
        #     input(f"{chapter_index}:第{data['chapter_index']}章")
        #     sync_cli.set('zhanshen_url', chapter_index)


    asyncio.run(run())
